package com.zhiyou100.blog.dao.impl;


import com.zhiyou100.blog.dao.MessageDao;
import com.zhiyou100.blog.entity.Message;
import com.zhiyou100.blog.entity.User;
import com.zhiyou100.blog.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author shkstart
 * @create 2021-10-22 18:03
 */
public class MessageDaoImpl implements MessageDao {
    @Override
    public List<Message> getListMessageWithTid(int tid) {
        try (Connection conn = JDBCUtils.getConnection();) {
            QueryRunner runner = new QueryRunner();
            String sql = "SELECT m.MID `mid`,m.mcontent,m.mcreate_time mcreateTime,m.uid,m.tid " +
                    "FROM tab_message m " +
                    "WHERE tid=? ";
            //ResultSetHandler<T> rsh 结果集的处理器
            //使用BeanListHandle的子类BeanHandler<T>
            BeanListHandler<Message> handler = new BeanListHandler<>(Message.class);
            List<Message> list = runner.query(conn, sql, handler, tid);
            return list;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public Integer appendMessage(Message message) {
        try (Connection conn = JDBCUtils.getConnection();) {
            QueryRunner runner = new QueryRunner();
            String sql = "insert into tab_message values(null,?,?,?,?)";
            return runner.update(conn, sql, message.getMcontent(), message.getMcreateTime()
                    , message.getUid(), message.getTid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Integer deleteMessageWithId(int id) {
        try (Connection conn = JDBCUtils.getConnection();) {
            QueryRunner runner = new QueryRunner();
            String sql = "delete from tab_message where mid= ? ";
            return runner.update(conn, sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Test
    public void test1() {
        System.out.println(getListMessageWithTid(1001));
    }

   /* @Override
    public List<Message> getListMessagePaging(int startIndex, int pageSize) {
        try (Connection conn = JDBCUtils.getConnection();) {
            QueryRunner runner = new QueryRunner();
            String sql = "select * from student limit ?,? ";
            //ResultSetHandler<T> rsh 结果集的处理器
            //使用BeanListHandle的子类BeanHandler<T>
            BeanListHandler<Message> handler = new BeanListHandler<>(Message.class);
            List<Message> list = runner.query(conn, sql, handler, startIndex, pageSize);
            return list;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }*/
}
